<template>
  <div ref="editor"></div>
  <!-- <button @click="syncHTML">同步内容</button> -->
  <!-- <div :innerHTML="content.html"></div> -->
</template>

<script>
import { onMounted, onBeforeUnmount, ref, reactive, toRefs, watch } from 'vue';
import WangEditor from 'wangeditor';

export default {
  name: 'app',
  props: {
    value: {
      type: String,
      default: '',
    },
    initValue: {
      type: String,
      default: '',
    },
  },
  setup(props, { emit }) {
    const editor = ref();
    const { initValue } = toRefs(props);
    const content = reactive({
      html: initValue.value,
      text: '',
    });
    let instance;
    onMounted(() => {
      instance = new WangEditor(editor.value);
      Object.assign(instance.config, {
        onchange() {
          content.html = instance && instance.txt && instance.txt.html();
          emit('update:value', content.html);
          emit('change', content.html);
        },
      });
      instance.config.height = 200;
      instance.create();
      instance.txt.html(content.html);
    });

    onBeforeUnmount(() => {
      instance.destroy();
      instance = null;
    });

    watch(
      () => initValue.value,
      key => {
        if (key) {
          instance.txt.html(key);
        } else {
          instance.txt.html('');
        }
      },
    );

    const setValue = (str = '') => {
      instance.txt.html(str);
    };

    return {
      //   syncHTML,
      editor,
      content,
      setValue,
    };
  },
  emits: {
    'update:value': null,
    change: null,
  },
};
</script>

<style lang="less" scoped></style>
